const WebSocket = require('ws');
const fs = require('fs');
const b64 = require('js-base64')

const pcm_file = './test2.txt';
let interval = 0,
  sampleRate = 8000,
  bytePerSample = 2,
  channels = 1,
  bytesChunk = (sampleRate * bytePerSample * channels),
  offset = 0,
  pcmData,
  wss;

// 本地读取文件流
// fs.readFile(pcm_file,  (err, data) => {
// fs.readFile(pcm_file, {encoding: 'utf-8'}, (err, data) => {
//   if (err) throw err;
//   // pcmData = data;
//   data = data.split(' ').join('')
//   pcmData =  Buffer.from(data, 'hex');
//   });


openSocket();
// 打开socket
function openSocket() {
  wss = new WebSocket.Server({ port: 8899 });
  console.log('Server ready...');
  wss.on('connection', function connection(ws) {
    ws.on('error', function (error) {``
      console.log('disconnected 断开连接')
    })

    console.log('Socket connected. sending data... ws已连接 发送数据');
    if (interval) {
      clearInterval(interval);
    }

    ws.on('message', function (data) {
      // pcmData = Buffer.from(convertUint8ToInt8(b64.Base64.toUint8Array(data)));
      pcmData = Buffer.from(data, 'base64');
      console.log('收到数据',pcmData, pcmData.length, Buffer.isBuffer(pcmData))
      interval = setInterval(function () {
        sendData();
      }, 500);
    });
  });
}

function convertUint8ToInt8(uintArray) {
  const intArray = new Int8Array(uintArray.length);
  for (let i = 0; i < uintArray.length; i++) {
      // 直接赋值会自动处理符号位，无需手动转换
      intArray[i] = uintArray[i];
  }
  return intArray;
}
// 发送数据
function sendData() {
  let payload;
  if (!pcmData || !pcmData.length) {
    console.log('无数据可发送');
    clearInterval(interval);
    offset = 0;
    return;
  }

  if (offset >= pcmData.length) {
    console.log('所有数据已发送');
    clearInterval(interval);
    offset = 0;
    return;
  }
if(Buffer.isBuffer(pcmData)) {
  payload = pcmData.subarray(offset, (offset + bytesChunk));
  console.log('pcmData is buffer', payload)
} else {
  payload =[]
}
  offset += bytesChunk;
  wss.clients.forEach(function each(client) {
    if (client.readyState === WebSocket.OPEN) {
      client.send(payload);
      console.log('发送成功',offset, pcmData.length)
    }
  });
}
